package com.defysoft.waukids.intro;

import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type.Bc_Student_Cus;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.R;
import com.defysoft.waukids.adapter.Adapter_IntroSelectStudent_L;
import com.defysoft.waukids.slide.Slide_MemberStudent_Connect_A;

public class Intro_SelectStudent_A extends BaseActivity implements OnClickListener{
	ListView listView;
	TextView addcode;
	Adapter_IntroSelectStudent_L adapter;
	ArrayList<Bc_Student_Cus> list;
	private SharedPreferences member;
	private SharedPreferences school;
	private SharedPreferences student;	//Adapter_IntroSelect에서 학생정보 입력.
	private final int SELECT_STUDENT = 1;
	private final int LOGOUT_THREAD = 2;
	
	final int FAIL_LOGOUT = 7;
	final int SUCCESS_LOGOUT = 8;
	private final int NONE_STUDENT = 9;
	private final int SUCCESS_SEARCH= 10;
	
	SharedPreferences.Editor editor; // 학생정보 여기서 넣기. student.edit();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intro__select_student_);
		setStartData();
	}
 
	@Override
	public void setStartData() {
		super.setStartData();
		listView=(ListView)findViewById(R.id.SELECT_STUDENT_LIST);
		member = getSharedPreferences("member", MODE_PRIVATE);
		school = getSharedPreferences("school", MODE_PRIVATE);
		student = getSharedPreferences("student", MODE_PRIVATE);
		addcode=(TextView)findViewById(R.id.SELECT_STUDENT_ADDCODE);
		addcode.setOnClickListener(this);
		findViewById(R.id.SELECT_STUDENT_LOGOUT).setOnClickListener((OnClickListener) this);	//로그아웃?뒤로가기?
	}
	
	@Override
	protected void onResume() {
		super.onResume();	
		if(member.getString("PK_Mem_Email", "")==""){
			endDIal();
			finish();
		}else {
			startNetwork(SELECT_STUDENT);			
		}
	}
	
	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		if (firstThread != null) {firstThread.interrupt();}
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case SELECT_STUDENT:	//메인
					mainThread();
					break;
				case LOGOUT_THREAD:
					logoutThread();
					break;
				}
			}
		});
		firstThread.start();
	}
	
	protected void logoutThread() {
		JSONObject jsonObject = null;
		try {
			
			jsonObject = new JSONObject(publicHttpCallback(HTTP_MEMBER_LOGOUT,
					"PK_Mem_Email=" + member.getString("PK_Mem_Email", "")));
			
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_LOGOUT, jsonObject.getString("payload"));
			} else {
				onNetworkCallback(FAIL_LOGOUT, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
	}

	public void mainThread(){
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_SELECT_MYSTUDENT,"email="+member.getString("PK_Mem_Email", "")));
			if (jsonObject.getBoolean("success")) {	
				list=JsonParser.SelectMyStudent(jsonObject.getString("payload"));

				onNetworkCallback(SUCCESS_SEARCH,"" );
			} else {
				onNetworkCallback(NONE_STUDENT, "");
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, "main"+e.toString());
		};	
	}
	
	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG).show();
			break;
		case NONE_STUDENT:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			Toast.makeText(this, "등록된 자녀가 없습니다. 자녀코드를 등록해주세요", Toast.LENGTH_LONG).show();
			break;
		case SUCCESS_SEARCH:
			endDIal();
			if (firstThread != null) {
				firstThread.interrupt();
			}
			//자녀가 한명이면 바로 main으로
			if (list.size() == 1) {
				editor = student.edit();
				editor.putString("PK_Stu_Code", list.get(0).PK_Stu_Code + "");
				editor.putString("FK_Sch_Stu_Code",list.get(0).FK_Sch_Stu_Code + "");
				editor.putString("FK_Cla_Stu_Code",list.get(0).FK_Cla_Stu_Code + "");
				editor.putString("FK_Bea_Stu_Code",list.get(0).FK_Bea_Stu_Code + "");
				editor.putString("Stu_Name", list.get(0).Stu_Name + "");
				editor.putString("Stu_Birth", list.get(0).Stu_Birth + "");
				editor.putString("Stu_Info", list.get(0).Stu_Info + "");
				editor.putString("Stu_Photo", list.get(0).Stu_Photo + "");
				editor.commit();
				
				startActivity(new Intent(Intro_SelectStudent_A.this, Intro_Main_A.class));
				finish();
				break;
			}

			
			adapter=new Adapter_IntroSelectStudent_L(this, 0, list,getLayoutInflater(),student.edit());
			listView.setAdapter(adapter);
			break;
		case SUCCESS_LOGOUT: // 로그아웃UUID삭제 성공.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			SharedPreferences.Editor editor = member.edit();
			editor.clear();
			editor.commit();
			startActivity(new Intent(Intro_SelectStudent_A.this, Intro_Intro_A.class));
			finish();
			Toast.makeText(this, "로그인창으로 이동됩니다.", Toast.LENGTH_SHORT).show();
			break;
		case FAIL_LOGOUT: // 로그아웃 UUID삭제 실패.
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_SHORT).show();
			break;
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.SELECT_STUDENT_LOGOUT:	//로그아웃, UUID털기.
			AlertDialog.Builder builder = new AlertDialog.Builder(
					Intro_SelectStudent_A.this);
			builder.setMessage(
					"로그아웃 하겠습니까?")
					.setCancelable(false)
					.setPositiveButton("네",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									startNetwork(LOGOUT_THREAD);
									dialog.cancel();
								}
							})
					.setNegativeButton("아니오",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							});
			AlertDialog alert = builder.create();
			alert.show();
			break;
		case R.id.SELECT_STUDENT_ADDCODE:	//자녀등록
			startActivity(new Intent(Intro_SelectStudent_A.this, Slide_MemberStudent_Connect_A.class)
			.putExtra("PK_Mem_Email", member.getString("PK_Mem_Email", "")));
			break;

		}
	}
	
	
}
